package com.example.tdemo.thread.container_not_safe;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

public class ContainerNotSafeDemo {

    public static void main(String[] args) {
        notSafeMap();
    }

    private static void notSafeMap() {
        // 线程不安全
        Map<String, String> set = new HashMap<>();
        // 线程安全
//        Map<String,String> set = new ConcurrentHashMap<>();
//        Map<String,String> set = new Hashtable<>();
//        Map<String,String> set = Collections.synchronizedMap(new HashMap<>());

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                set.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }, String.valueOf(i)).start();
        }
    }

    private static void notSafeSet() {
        // 线程不安全
        Set<String> set = new HashSet<>();
        // 线程安全
//        Set<String> set = new CopyOnWriteArraySet<>();
//        Set<String> set = Collections.synchronizedSet(new HashSet<>());

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }, String.valueOf(i)).start();
        }
    }

    private static void notSafeList() {
        // 线程不安全
//        List<String> list = new ArrayList<>();
        // 线程安全
//        List<String> list = new Vector<>();
//        List<String> list = Collections.synchronizedList(new ArrayList<>());
        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, String.valueOf(i)).start();
        }
    }


}
